<?php

namespace backend\controllers;

use backend\models\MallDiscount;
use backend\models\MallDistribution;
use backend\models\MallProductSpecs;
use backend\models\Model;
use Yii;
use backend\models\MallProduct;
use backend\models\MallProductSearch;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MallProductController implements the CRUD actions for MallProduct model.
 */
class MallProductController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all MallProduct models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MallProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if (Yii::$app->request->post('hasEditable')) {
            $id = Yii::$app->request->post('editableKey');
            $model = MallProduct::findOne(['id' => $id]);
            $output = '';
            $posted = current($_POST['MallProduct']);
            $post = ['MallProduct' => $posted];
            if ($model->load($post)) {
                $model->save();
                isset($posted['sort']) && $output = $model->sort;
            }
            $out = Json::encode(['output' => $output, 'message' => '']);
            return $out;
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single MallProduct model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new MallProduct model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new MallProduct();
        $modelsMallProductSpecss = [new MallProductSpecs];

//        $discount = MallDiscount::find()->where(['state'=>1])->one();
//        $distribution = MallDistribution::find()->where(['state'=> 1])->one();
        $distribution = MallDistribution::find()->where(['id'=> 1])->one();
        if ($model->load(Yii::$app->request->post())) {
            $model->up_time = time();
            $model->create_time = time();
            $model->update_time = time();
            $model->no = "NO." . $model->createNoncestr(20);
            $model->level_one = $model->old_price  * $distribution->level_one;
            $model->level_two = $model->old_price  * $distribution->level_two;
            $model->save();
            $modelsMallProductSpecss = Model::createMultiple(MallProductSpecs::class);
            Model::loadMultiple($modelsMallProductSpecss, Yii::$app->request->post());
//            var_dump($modelsMallProductSpecss);
//            return 111;

            // validate all models
//            $valid = $model->validate();
//            $valid = Model::validateMultiple($modelsMallProductSpecss) && $valid;
//
//            if ($valid) {
//                $transaction = \Yii::$app->db->beginTransaction();
//                try {
//                    if ($flag = $model->save(false)) {
//                        foreach ($modelsMallProductSpecss as $modelMallProductSpecss) {
//                            $modelMallProductSpecss->pid = $model->id;
//                            $modelMallProductSpecss->create_time = time();
//                            if (! ($flag = $modelMallProductSpecss->save(false))) {
//                                $transaction->rollBack();
//                                break;
//                            }
//                        }
//                    }
//                    if ($flag) {
//                        $transaction->commit();
//                        return $this->redirect(['view', 'id' => $model->id]);
//                    }
//                } catch (Exception $e) {
//                    $transaction->rollBack();
//                }
//            }

            foreach ($modelsMallProductSpecss as $modelMallProductSpecs) {
                $modelMallProductSpecs->pid = $model->id;
                $modelMallProductSpecs->create_time = time();
                $modelMallProductSpecs->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }
//        $objects[0] = new MallProductSpecs;
//        $objects[1] = new MallProductSpecs;
//        $objects[2] = new MallProductSpecs;
//        $objects[3] = new MallProductSpecs;
//        $objects[4] = new MallProductSpecs;
//        $objects[5] = new MallProductSpecs;
//        $objects[6] = new MallProductSpecs;
//        $objects[7] = new MallProductSpecs;
//        $objects[8] = new MallProductSpecs;
//        $objects[9] = new MallProductSpecs;

        return $this->render('create', [
            'model' => $model,
            'modelsMallProductSpecss' => (empty($modelsMallProductSpecss)) ? [new MallProductSpecs] : $modelsMallProductSpecss
//            'modelsMallProductSpecss' => $objects,
        ]);
    }

    /**
     * Updates an existing MallProduct model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelSku = MallProductSpecs::find()->where(['pid'=> $id,'status' => 1])->all();


//        var_dump(Yii::$app->request->post()['MallProduct']['mid']);
//        unset(Yii::$app->request->post()['MallProduct']['mid']);
//        var_dump(Yii::$app->request->post());
//        exit;

        if ($model->load(Yii::$app->request->post())) {

//            $discount = MallDiscount::find()->where(['state'=>1])->one();
            $distribution = MallDistribution::find()->where(['id'=> 1])->one();

            $model->update_time = time();
            $model->level_one = $model->old_price *  $distribution->level_one;
            $model->level_two = $model->old_price *  $distribution->level_two;
            $model->save();
            //MallProductSpecs::deleteAll(['pid'=> $id]);
            //修改商城的
            MallProductSpecs::updateAll(['status' => -1],['pid'=> $id]);
            $sku = Yii::$app->request->post('MallProductSpecs');
            $data = [];
            foreach ($sku as $key => $value) {
                $data[] = [
                    'pid' => $id,
                    'value' => $value['value'],
                    'img' => $value['img'],
                    'stock' => $value['stock'],
                    'price' => $value['price'],
                    'create_time' => time()
                ];
            }
            Yii::$app->db->createCommand()->batchInsert('mall_product_specs', [
                'pid',
                'value',
                'img',
                'stock',
                'price',
                'create_time'
            ], $data)->execute();

            //查找出 parent_id = id 的集合

            //循环更新每一个集合对象

            //更新商家parent_id = id 的mall_product 表

            //删除pid = parent_id 中id  然后插入specs
            $products = MallProduct::find()->where(['parent_id' => $model->id, 'status' => 1])->all();
            $dataUnset = Yii::$app->request->post();
            unset($dataUnset['MallProduct']['mid']);
            foreach ($products as $product) {
                if ($product->load($dataUnset) ) {
                    $product->update_time = time();
                    $product->level_one = $product->old_price *  $distribution->level_one;
                    $product->level_two = $product->old_price *  $distribution->level_two;
                    $product->save();
                    //MallProductSpecs::deleteAll(['pid'=> $product->id]);
                    MallProductSpecs::updateAll(['status' => -1],['pid'=> $product->id]);
                    $dataSku = [];
                    foreach ($sku as $_key => $_value) {
                        $dataSku[] = [
                            'pid' => $product->id,
                            'value' => $_value['value'],
                            'img' => $_value['img'],
                            'stock' => $_value['stock'],
                            'price' => $_value['price'],
                            'create_time' => time(),
                            'status' => 1
                        ];
                    }
                    Yii::$app->db->createCommand()->batchInsert('mall_product_specs', [
                        'pid',
                        'value',
                        'img',
                        'stock',
                        'price',
                        'create_time',
                        'status'
                    ], $dataSku)->execute();
                }

            }



            return $this->redirect(['view', 'id' => $model->id]);
        }

        if (null == $modelSku) {
            $mallProductSpecsOne = new MallProductSpecs();
            $mallProductSpecsOne->id = '';
            $mallProductSpecsOne->pid = $id;
            $mallProductSpecsOne->value = '';
            $mallProductSpecsOne->stock = '';
            $mallProductSpecsOne->price = '';
            $mallProductSpecsOne->product_no = '';
            $mallProductSpecsOne->create_time = '';
            $mallProductSpecsOne->img = '';
            $modelSku[0] = $mallProductSpecsOne;
        }

        return $this->render('update', [
            'model' => $model,
            'modelSku' => $modelSku,
        ]);
    }

    /**
     * Deletes an existing MallProduct model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the MallProduct model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return MallProduct the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = MallProduct::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
